﻿using AuSys.Services.App.UserInfo;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace AuSys.Services.App.Authentication
{
    public class JwtTokenIssueService(
        IConfiguration config)
    {
        public string GetToken(int uid, int expireHrs, List<Claim>? moreClaims = null)
        {
            string domain = config["Jwt:Domain"] ?? throw new Exception("未找到配置项Jwt:Domain");
            string secret = config["Jwt:SecretKey"] ?? throw new Exception("未找到配置项Jwt:SecretKey");

            var claims = new List<Claim>{
                new(HttpUserIdProvider.UserIdClaimName, uid.ToString())
            };
            if(moreClaims is { })
                claims.AddRange(moreClaims);
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: domain,
                audience: domain,
                claims: claims,
                expires: DateTime.Now.AddHours(expireHrs),
                signingCredentials: creds
            );
            string tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
            return tokenStr;
        }
    }
}
